import api from '../../api';
import { message } from 'antd';
import moment from 'moment';

export default {
  namespace: 'nonstandarmaintenanceNewM', //非标产品
  state: {
    listRefresh: false, //列表刷新
    dictMap: {}, // 未经过处理的字典值
    dictMapSelect: {}, // 用于搜索页面搜索条件的所有下拉框的字典值
  },
  effects: {
    //保存表单接口
    *saveData({ payload, callback }, { call, put }) {
      const response = yield call(api.nonstandarmaintenanceNew.saveData, payload);
      if (response.code == 0) {
        message.success('保存成功');
        callback(true);
      } else {
        message.error(response?.msg || '保存表单失败');
        callback(false);
        return;
      }
    },
    //字典key
    *fetchDictByKeys({ payload }, { call, put }) {
      const response = payload['dictData'];
      if (response) {
        let dictMapSelect = {};
        Object.getOwnPropertyNames(response).forEach(function (key) {
          if (response[key]) {
            dictMapSelect[key] = response[key].map((ele) => {
              return { value: ele.code, title: ele.value };
            });
          }
        });
        yield put({
          type: 'save',
          payload: {
            dictMap: response,
            dictMapSelect,
          },
        });
      } else {
        message.error(`查询数据字典失败，失败原因：`);
      }
    },
    //主体信用评级机构
    *getMainRatingDepartData({ payload, callback }, { call, put }) {
      const res = yield call(api.nonstandarmaintenanceNew.mainRatingDepart, payload);
      if (res && res.code == 0) {
        callback('success', res.data);
      } else {
        callback('fail');
        message.error(`查询主体信用评级机构列表失败，失败原因：${res?.msg}`);
        console.error(`查询主体信用评级机构列表失败，失败原因：${res?.msg}`, '接口名称： mainRatingDepart 接口：nonstandard/mainRatingDepart');
      }
    },
    //债项信用评级机构
    *getDebtRatingDepartData({ payload, callback }, { call, put }) {
      const res = yield call(api.nonstandarmaintenanceNew.debtRatingDepart, payload);
      if (res && res.code == 0) {
        callback('success', res.data);
      } else {
        callback('fail');
        message.error(`查询债项信用评级机构列表失败，失败原因：${res?.msg}`);
        console.error(`查询债项信用评级机构列表失败，失败原因：${res?.msg}`, '接口名称： debtRatingDepart 接口：nonstandard/debtRatingDepart');
      }
    },
    /**************  列表相关接口 *****************/
    // 获取列表-非标准化债券类资产
    *getAssetTableData({ payload, callback }, { call, put, select }) {
      const res = yield call(api.nonstandarmaintenanceNew.getAssetTableData, payload);
      if (res && res.code == 0) {
        let dictMapSelectData = yield select((state) => state.nonstandarmaintenanceNewM.dictMapSelect);

        // 资产类别
        let assetTypeData = dictMapSelectData['ASSETS_ASSET_TYPE'];
        // 计息基础
        let interestBasisData = dictMapSelectData['ASSETS_INTEREST_BASIS'];
        // 融资人主体评级  资产外部评级
        let mainRatingStartData = dictMapSelectData['ASSETS_MAIN_RATING_START'];

        res.data.columns &&
          res.data.columns.map((item) => {
            if (item.dataIndex == 'interestBasis') {
              // 计息基础 前端翻译
              item.render = (text, record, index) => {
                if (text === null || text === undefined) {
                  return '--';
                } else {
                  if (isNaN(text)) {
                    return text;
                  } else {
                    let temp = interestBasisData?.length && interestBasisData.find((item) => item.value == text);
                    return temp ? temp.title : text;
                  }
                }
              };
            }

            if (item.dataIndex == 'mainRatingStart' || item.dataIndex == 'debtRatingStart') {
              // 融资人主体评级  资产外部评级   前端翻译
              item.render = (text, record, index) => {
                if (text === null || text === undefined) {
                  return '--';
                } else {
                  if (isNaN(text)) {
                    return text;
                  } else {
                    let temp = mainRatingStartData?.length && mainRatingStartData.find((item) => item.value == text);
                    return temp ? temp.title : text;
                  }
                }
              };
            }
            if (item.dataIndex == 'assetType') {
              // 资产类别   前端翻译
              item.render = (text, record, index) => {
                if (text === null || text === undefined) {
                  return '--';
                } else {
                  if (isNaN(text)) {
                    return text;
                  } else {
                    let temp = assetTypeData?.length && assetTypeData.find((item) => item.value == text);
                    return temp ? temp.title : text;
                  }
                }
              };
            }
            if (item.key == 'assetType' || item.key == 'tradingcode') {
              item.width = '150px';
              item.fixed = 'left';
            }
            if (item.key == 'tradingname') {
              item.width = '200px';
              item.type = 'maxContent';
              item.fixed = 'left';
            }
            if (item.key == 'issueScale') {
              // 金额
              item.type = 'money';
            }
            if (item.key === 'name') {
              // 名称
              item.width = '200px';
              item.type = 'maxContent';
            }
            if (item.key == 'fixedRate') {
              // 项目收益率（利率）
              item.toFixed = 5;
              item.type = 'rate';
            }
          });
        callback('success', res.data);
      } else {
        callback('fail');
        message.error(`获取非标准化债券类资产列表失败，失败原因：${res?.msg}`);
        console.error(`获取非标准化债券类资产列表失败，失败原因：${res?.msg}`, '接口名称： queryTable 接口：instrument-server/nonstandard/queryTable');
      }
    },
    // 获取列表-非标准化债券类投资
    *getInvestTableData({ payload, callback }, { call, put, select }) {
      const res = yield call(api.nonstandarmaintenanceNew.getInvestTableData, payload);
      if (res && res.code == 0) {
        let dictMapSelectData = yield select((state) => state.nonstandarmaintenanceNewM.dictMapSelect);

        // 交易流通场所
        let jsltPlaceData = dictMapSelectData['INVEST_JYLTCS'];
        // 类型
        let typeData = dictMapSelectData['INVEST_TYPE'];
        res.data.columns &&
          res.data.columns.map((item) => {
            if (item.dataIndex == 'jsltPlace') {
              // 交易流通场所   前端翻译
              item.render = (text, record, index) => {
                if (text === null || text === undefined) {
                  return '--';
                } else {
                  if (isNaN(text)) {
                    return text;
                  } else {
                    let temp = jsltPlaceData?.length && jsltPlaceData.find((item) => item.value == text);
                    return temp ? temp.title : text;
                  }
                }
              };
            }
            if (item.dataIndex == 'type') {
              // 类型   前端翻译
              item.render = (text, record, index) => {
                if (text === null || text === undefined) {
                  return '--';
                } else {
                  if (isNaN(text)) {
                    return text;
                  } else {
                    let temp = typeData?.length && typeData.find((item) => item.value == text);
                    return temp ? temp.title : text;
                  }
                }
              };
            }
            if (item.key == 'tradingcode') {
              item.width = '150px';
              item.fixed = 'left';
            }
            if (item.key == 'tradingname') {
              item.width = '200px';
              item.type = 'maxContent';
              item.fixed = 'left';
            }
            if (item.key == 'totalNum') {
              item.type = 'money';
            }
            if (item.key == 'rate') {
              // 贴现利率(%)
              item.toFixed = 5;
              item.type = 'rate';
            }
            if (item.key == 'isProfit' || item.key == 'isBelongBugSold') {
              // 是否为收/受益权  和 是否属于买入返售
              item.render = (text, record, index) => {
                if (text === null || text === undefined) {
                  return '--';
                } else {
                  if (isNaN(text)) {
                    return text;
                  } else {
                    return text == 1 ? '是' : '否';
                  }
                }
              };
            }
          });
        callback('success', res.data);
      } else {
        callback('fail');
        message.error(`获取非标准化债券类投资列表失败，失败原因：${res?.msg}`);
        console.error(`获取非标准化债券类投资列表失败，失败原因：${res?.msg}`, '接口名称： queryInveTypeTable 接口：instrument-server/nonstandard/queryInveTypeTable');
      }
    },
    // 删除数据
    *deleteById({ payload, callback }, { call, put }) {
      const res = yield call(api.nonstandarmaintenanceNew.deleteById, payload);
      if (res && res.code == 0) {
        callback('success');
        message.success('删除成功');
      } else {
        callback('fail');
        message.error(`删除失败，失败原因：${res?.msg}`);
        console.error(`删除失败，失败原因：${res?.msg}`, '接口名称： deleteOne 接口：instrument-server/nonstandard/deleteOne');
      }
    },
    // 根据id获取详情
    *getDataById({ payload, callback }, { call, put }) {
      const res = yield call(api.nonstandarmaintenanceNew.getDataById, payload);
      if (res && res.code == 0 && JSON.stringify(res.data) != '{}') {
        callback('success', res.data);
      } else {
        callback('fail');
        message.error(`根据id获取详情失败，失败原因：${res?.msg}`);
        console.error(`根据id获取详情失败，失败原因：${res?.msg}`, '接口名称： queryOne 接口：instrument-server/nonstandard/queryOne');
      }
    },
    //计算付息
    *calcFx({ payload, callback }, { call, put }) {
      const response = yield call(api.nonstandarmaintenanceNew.calcFx, payload);
      if (response && response.code == 0) {
        let data = response.data.dataSource || [];
        data &&
          data.map((item) => {
            if (moment(item.endDate) < moment()) {
              //到期日小于当前日期 则不可修改
              item.disable = 1;
            }
          });
        data.sort(function (a, b) {
          if (moment(a?.startDate).format('YYYY-MM-DD') == moment(b?.startDate).format('YYYY-MM-DD')) {
            moment(a?.endDate).format('YYYY-MM-DD') > moment(b?.endDate).format('YYYY-MM-DD') ? 1 : -1;
          }
          return moment(a?.startDate).format('YYYY-MM-DD') > moment(b?.startDate).format('YYYY-MM-DD') ? 1 : -1;
        });
        callback(data);
      } else {
        callback();
        message.error(`付息计算失败，失败原因：${response?.message}`);
        console.error(`付息计算失败，失败原因：${response?.message}`, '接口名称： queryJsFx 接口：nonstandard/queryJsFx');
      }
    },
    // 行业下拉数据
    *getIndustryData({ payload, callback }, { call, put }) {
      const res = yield call(api.getIndustry, payload);
      if (res && res.code == 0 && JSON.stringify(res.data) != '{}') {
        callback('success', res.data);
      } else {
        callback('fail');
        message.error(`获取行业数据失败，失败原因：${res?.msg}`);
        console.error(`获取行业数据失败，失败原因：${res?.msg}`, '接口名称： getTree 接口：instrument-server/industry/getTree');
      }
    },

    *listRefresh({ payload, callback }, { call, put }) {
      yield put({
        type: 'save',
        payload: {
          listRefresh: payload.listRefresh,
        },
      });
    },
    //查询付息金额
    *queryInterestpayment({ payload, callback }, { call, put }) {
      const res = yield call(api.nonstandarmaintenanceNew.queryInterestpayment, payload);
      if (res && res.code == 0) {
        callback(res.data);
      } else {
        callback();
        message.error(`${res?.message || '获取付息金额失败！'}`);
      }
    },
  },
  reducers: {
    save(state, { payload }) {
      return { ...state, ...payload };
    },
  },
};
